<template>
  <el-tree ref="treeRef" :data="menuList" show-checkbox node-key="id" :props="defaultProps"
    :default-checked-keys="resourceIdList" :default-expanded-keys="resourceIdList" :renderContent="renderContent"
    render-after-expand @check="checkChange">
  </el-tree>
</template>

<script lang="ts" setup>
import { reqAllMenuTree } from "@/api/business/menu";
import { reqResourceRoleRelation } from "@/api/business/role";
import { store } from "@/store";
import { Tree } from "element-plus/es/components/tree-v2/src/types";
const defaultProps = {
  children: "children",
  label: "label",
};
const props = defineProps({
  resourceIdList: {
    type: [Array],
    default: [],
  },
});
// 默认选中和展开的节点
const resourceIdList = computed(() => {
  let arr: string[] = [];
  props.resourceIdList.forEach((item) => {
    if (!arr.includes(item.id)) {
      arr.push(item.id);
    }
  });
  return arr;
});
const treeRef = ref();
// 当前选中的节点
const menuList = ref([]);

// 清空选中的按钮权限
const clearNodes = (nodes: any = []) => {
  nodes.forEach((item) => {
    let node = treeRef.value.getNode(item.id);
    collapseAllChildren(node);
    node.collapse();
    if (!(item.children && item.children.length)) {
      item.checked = false;
      item.buttonList.map(v => {
        v.selected = false
        return v
      })
    }
    if (item.children && item.children.length) clearNodes(item.children);
  });
};
const readNodes = (nodes: any = [], arr: any = []) => {
  for (let item of nodes) {
    item.label = item.name;
    // item.selected = false;
    if (resourceIdList.value.filter((v) => v == item.id).length) {
      // console.log(resourceIdList.value);
      let menu = props.resourceIdList.find(v => v.id === item.id);
      // console.log('获取的菜单', menu);
      if (!(item.children && item.children.length)) {
        item.checked = true
        item.buttonList.map(v => {
          v.selected = false
          if (menu) {
            for (let i = 0; i < menu.button.length; i++) {
              if (v.id === menu.button[i]) {
                v.selected = true;
              }
            }
          }
          return v
        })
      }
    };
    if (item.children && item.children.length) readNodes(item.children);
  }
};
// 展示和隐藏右边按钮
const checkNodes = (nodes: any[], isCheck: Boolean) => {
  nodes.forEach((item) => {
    if (item.children && item.children.length) checkNodes(item.children, isCheck);
    if (item.buttonList.length && item.resourceType === 2) {
      item.checked = isCheck;
    };
  });
};
// 递归子代及后代展开
const expandAllChildren = (node: object) => {
  if (node.childNodes && node.childNodes.length > 0) {
    for (let i = 0; i < node.childNodes.length; i++) {
      const childNode = node.childNodes[i];
      if (!childNode.isLeaf && !childNode.expanded) {
        childNode.expand();
      }
      expandAllChildren(childNode); // 递归调用展开子节点的子节点
    }
  }
};
// 递归子代及后代关闭
const collapseAllChildren = (node: object) => {
  // console.log('zzz', node);
  if (node.childNodes && node.childNodes.length > 0) {
    for (let i = 0; i < node.childNodes.length; i++) {
      const childNode = node.childNodes[i];
      if (childNode.expanded) {
        childNode.collapse();
        collapseAllChildren(childNode); // 递归调用关闭子节点的子节点
      }
    }
  }
};
// 展开和关闭其下所有子节点
const expandNodes = (data: Object) => {
  let node = treeRef.value.getNode(data.id);
  //展开选中的未展开的非叶子节点
  if (node.checked && !node.expanded && !node.isLeaf) {
    node.expand(() => {
      expandAllChildren(node);
    });
  }
  //关闭取下勾选的节点的所有子代节点
  if (!node.checked && node.expanded && !node.isLeaf) {
    collapseAllChildren(node);
    node.collapse();
  }
};
const checkChange = (data, selectNode,) => {
  const isCheck = treeRef.value.getCheckedNodes().indexOf(data) > -1
  expandNodes(data);
  checkNodes([data], isCheck);
  console.log('获取所有选中的节点', getCheckedNodes());
};
const renderContent = (h, { node, data, store }: { node: Node, data: Tree, store: Node['store'] }) => {
  // console.log(node, data, store);
  let checkbox = [];
  data.buttonList.forEach(item => {
    checkbox.push(h(ElCheckbox, {
      props: {
        value: item.selected
      },
      modelValue: item.selected,
      'onUpdate:modelValue': (value: any) => {
        item.selected = value;
      },
    }, { default: () => item.buttonName }))
  });
  return h(
    'span',
    {
      class: 'custom-tree-node',
    },
    h('span', null, node.label),
    data.checked ? h(
      'span',
      {
        class: 'custom-checkbox'
      },
      checkbox,
    ) : '',
  )
};
// 获取所有选中的节点
const getCheckedNodes = () => {
  let arr = [];
  let nodes = treeRef.value.getCheckedNodes();
  console.log('111', nodes);
  nodes.forEach((val) => {
    arr.push(val.id);
    val.buttonList.forEach((v) => {
      if (v.selected) arr.push(v.id);
    });
  });
  return arr;
};
// 获取已选中的节点和按钮
const getTreeData = () => {
  readNodes(menuList.value);
};
// 清空选中树
const clearTree = () => {
  treeRef.value.setCheckedKeys([]);
  // 清空选中的按钮权限
  clearNodes(menuList.value);
  menuList.value = [];

};


defineExpose({ clearTree, getCheckedNodes, getTreeData, menuList, });
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.custom-checkbox {
  white-space: pre-wrap;
}
</style>
<style scoped>
/* /deep/ .el-tree-node__content {
  height: undefined !important;
} */
</style>
